import _ from 'lodash';
import axios from 'axios';
import qs from 'qs';
import defaults from './defaults';
import interceptors from './interceptors';
import { RequestEnum } from '@/enums/httpEnum';

const instance = axios.create(Object.assign(axios.defaults, defaults));

interceptors(instance);

class Http {
    private instance = instance;
    request(method: string, url: string, data?: any, config?: questConfig): Promise<any> {
        if (data) {
            Object.keys(data).forEach((item) => {
                if (_.isNull(data[item]) || data[item] === '') {
                    delete data[item];
                }
            });
        }

        if (method === RequestEnum.GET) {
            if (data) {
                const query = qs.stringify(data, { indices: false });
                url += `?${query}`;
            }

            const result = _.isObject(config) ? { ...config } : {};
            return this.instance.get(url, {
                ...result,
            });
        }

        data = (config as any)?.stringify === true || config === true ? qs.stringify(data) : data;

        if (_.isObject(config) && Object.keys(config).length > 0) {
            return (this.instance as NormalObj)[method](url, data, {
                ...config,
            });
        }

        return (this.instance as NormalObj)[method](url, data);
    }

    // get请求方式
    Get(url: string, data?: any, type?: questConfig) {
        return this.request(RequestEnum.GET, url, data, type);
    }

    // post请求方式
    Post(url: string, data?: any, type?: questConfig) {
        return this.request(RequestEnum.POST, url, data, type);
    }

    // put请求方式
    Put(url: string, data?: any, type?: questConfig) {
        return this.request(RequestEnum.PUT, url, data, type);
    }

    // delete请求方式
    Delete(url: string, data?: any, type?: questConfig) {
        return this.request(RequestEnum.DELETE, url, data, type);
    }

    async Download(url: string, data?: any, type?: questConfig, name?: string) {
        console.log(name);
        const res = await this.request(RequestEnum.GET, url, data, type);
        // const { t } = useI18n();
        const blob = new Blob([res as BlobPart], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
        });
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = name + '.xlsx';
        a.style.display = 'none';
        document.body.appendChild(a);
        a.remove();
        a.click();
    }
}
export { instance };
export default new Http();
